package com.ruoyi.common.core.utils.file;

import com.ruoyi.common.core.exception.file.FileUploadException;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Objects;

/**
 * @author: Larry
 * @Date: 2024 /03 /26 / 18:57
 * @Description:
 */
public class FileTransformUtil {
    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;

    }

    /**
     * file转MultipartFile
     *
     *
     * @return MultipartFile
     */
    public File convertMultipartFileToFile(MultipartFile multipartFile) throws IOException {
        File file = new File(Objects.requireNonNull(multipartFile.getOriginalFilename()));
        multipartFile.transferTo(file);
        return file;
    }


    private static void inputStreamToFile(InputStream ins, File file) throws FileUploadException {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            throw new FileUploadException("读取文件错误", e);
        }
    }
}
